package users

import (
	"context"
	"encoding/json"
	"github.com/gorilla/websocket"
	"log"
	"smart-health-platforms/inits"

	"strconv"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

// 定义生产者连接映射（发送者）
var (
	ProduceConn = make(map[string]*websocket.Conn) // 存储生产者连接
	UserConn    = make(map[string]*websocket.Conn) // 存储用户连接
)

type RabbitmqMessageLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRabbitmqMessageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RabbitmqMessageLogic {
	return &RabbitmqMessageLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

type AAA struct {
	SenderID   int
	ReceiverID int
	Content    string
	Type       int64
	IsRead     int
}

func (l *RabbitmqMessageLogic) RabbitmqMessage(req *types.RabbitmqMessageRequest) (resp *types.Response, err error) {
	// 创建RabbitMQ实例
	rabbitmq := inits.NewRabbitMQSimple("user_message_queue")
	defer rabbitmq.Destory()

	// 获取消费通道
	msgs, _ := rabbitmq.ConsumeSimple()
	forever := make(chan bool)
	// 启动协程处理消息
	go func() {
		for d := range msgs {

			//// 解析消息
			var message AAA
			if err = json.Unmarshal(d.Body, &message); err != nil {
				log.Printf("解析消息失败: %v, 消息体: %s", err, d.Body)
				continue
				//}
			}
			conn := UserConn[strconv.Itoa(message.ReceiverID)]
			conn.WriteMessage(websocket.TextMessage, d.Body)
		}
	}()
	<-forever
	return
}
